﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace System.Diagnostics
{
    /// <summary>
    /// 表示进程<see cref="Process"/>的服务扩展
    /// </summary>
    /// <creator>marc</creator> 
    public static class ProcessExtensions
    {
        /// <summary>
        /// 异步等待退出
        /// </summary>
        /// <param name="process">进程对象</param>
        /// <param name="cancellationToken">退出标记</param>
        /// <returns></returns>
        public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
        {
            var tcs = new TaskCompletionSource<bool>();

            void Process_Exited(object sender, EventArgs e)
            {
                Task.Run(() => tcs.TrySetResult(true));
            }

            process.EnableRaisingEvents = true;
            process.Exited += Process_Exited;

            try
            {
                if (process.HasExited)
                {
                    return;
                }

                using (cancellationToken.Register(() => Task.Run(() => tcs.TrySetCanceled())))
                {
                    await tcs.Task;
                }
            }
            finally
            {
                process.Exited -= Process_Exited;
            }
        }
    }
}
